package com.hitqz.robot.driver.util;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Slf4j
public class KcCacheUtil {

    // 运行状态
    public static final String KEY_RUNNING_STATUS = "RUNNING_STATUS";
    // 导航状态
    public static final String KEY_NAV_STATUS = "NAV_STATUS";
    // 空气传感器状态（不走科聪底盘，后台直接和传感器通讯，建议使用转网口模块，让传感器主动上传消息，后台只要解析数据就好）
    public static final String KEY_AIR_SENSOR_STATUS = "AIR_SENSOR_STATUS";
    // 机器人控制模式
    private static final String KEY_CMD_SPEED = "CMD_SPEED_FLAG";

    public static final String KEY_CURRENT_STATION = "CURRENT_STATION";

    public static final String KEY_ROBOT_RUNNING_STATUS = "KEY_ROBOT_RUNNING_STATUS";

    private static final Cache<String, Boolean> speedFlagCache = CacheBuilder.newBuilder()
            .maximumSize(1)
            .expireAfterWrite(500, TimeUnit.MILLISECONDS) // 缓存过期时间
            .build();

    private static final Cache<String, String> varCache = CacheBuilder.newBuilder()
            //.maximumSize(50)
            //.expireAfterWrite(10, TimeUnit.SECONDS) // 缓存过期时间
            .build();

    private static final Cache<String, Object> cache = CacheBuilder.newBuilder()
            .maximumSize(100)// fixme 缓存最大容量,按key实际种类去扩容
            .expireAfterWrite(3, TimeUnit.SECONDS) // 缓存过期时间
            .build();

    public static void put(String key, Object value) {
        cache.put(key, value);
    }

    public static Object get(String key) {
        return cache.getIfPresent(key);
    }

    public static void setSpeedFlag(){
        speedFlagCache.put(KEY_CMD_SPEED, true);
    }

    public static boolean getSpeedFlag(){
        return Optional.ofNullable( speedFlagCache.getIfPresent(KEY_CMD_SPEED)).orElse(false);
    }

    public static void setVarCache(String varName,String varValue){
        varCache.put(varName,varValue);
    }

    public static String getVarCache(String varName){
        String value = varCache.getIfPresent(varName);
        //if (StrUtil.isNotBlank(value)){
        //    varCache.invalidate(varName);
        //}
        //log.info("{}---read result {}", varName, value);
        return value;
    }

}
